var http = require('http');
var fs = require('fs');
var readline = require('readline');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var __host = '/etc/hosts';
var __regName = 'regcenter';
var __port = 9981;

var __thisNodeName = 'mongodb_node1';
var __need = ['aa'];

function Abc() {}
util.inherits(Abc, EventEmitter);

Abc.prototype.getRegCenterIp = function() {
	var self = this;
	console.log('getRegCenterIp');
	var rd = readline.createInterface({
		input: fs.createReadStream('/etc/hosts'),
		output: process.stdout,
		terminal: false
	});

	var reg = /\s+/g;
	rd.on('line', function(line) {
		// console.log(line);
		var str = line.trim().replace(reg, ' ');
		var arr = str.split(' ');
		if (__regName === arr[1]) {
			console.log('find regcenter', line);
			self.regCenterIp = arr[0];
			self.emit('regCenterIp');
			return;
		}
	});
};

Abc.prototype.getSelfIp = function() {
	console.log('getSelfIp');
	var ifaces = require('os').networkInterfaces();
	var ips = {};
	for (var dev in ifaces) {
		ifaces[dev].forEach(function(details) {
			if (details.family === 'IPv4') {
				ips[dev] = details.address;
			}
		});
	}
	this.selfIp = ips.eth0 || ips.wlan0;
	return this.selfIp;
};

Abc.prototype.register = function() {
	var self = this;
	var options = {
		host: self.regCenterIp,
		port: __port,
		path: '/set?name=' + __thisNodeName + '&ip=' + self.selfIp,
		method: 'GET'
	};
	console.log('register ', options);
	var req = http.request(options, function(res) {
		console.log('status: ' + res.statusCode);
		if (res.statusCode === 200) {
			self.emit('regResult', true);
		} else {
			self.emit('regResult', false);
		}
	});
	req.end();
};

Abc.prototype.getByName = function(name) {
	console.log('getByName ' + name);
	var self = this;
	var options = {
		host: self.regCenterIp,
		port: __port,
		path: '/get?name=' + name,
		method: 'GET'
	};

	var req = http.request(options, function(res) {
		console.log('status: ' + res.statusCode);
		res.setEncoding('utf8');
		res.on('data', function(chunk) {
			console.log('body: ' + chunk);
			var result = JSON.parse('' + chunk).result;
			self.emit('getIp', {
				name: name,
				ip: result
			});
		});
	});
	req.end();
}

var abc = new Abc();
abc.getSelfIp();
abc.getRegCenterIp();

abc.on('regCenterIp', function() {
	this.register();
});

abc.on('regResult', function(isSucc) {
	if (!isSucc) {
		abc.register();
	} else {
		abc.getByName(__thisNodeName);
	}
});

abc.on('getIp', function(json) {
	console.log(json);
});